import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { Role } from '@/util/enum'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { adminRouter } from './adminRouter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/login',
      name: 'login',
      meta: {
        title: '用户登录',
      },
      // component: () => import('../views/UserLogin.vue'),
      component: () => import('../views/admin/AdminIndex.vue'),
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/admin/AdminIndex.vue'),
      meta: {
        title: '校友系统管理员',
        requireAuth: true,
        roles: [Role.Admin],
      },
      //此处使用静态导入后面可以改为动态导入
      children: [],
    },
    {
      path: '/alumni',
      name: 'alumni',
      component: () => import('../views/alumni/AlumniIndex.vue'),
      meta: {
        requireAuth: true,
        roles: [Role.Alumni],
      },
      children: adminRouter,
    },
    {
      path: '/student',
      name: 'student',
      component: () => import('../views/student/StudentIndex.vue'),
      meta: {
        requireAuth: true,
        roles: [Role.Student],
      },
      children: [],
    },
  ],
})

//前置路由守卫
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  // const useStore = useUserStore()
  // const role = useStore.userInfo.role
  if (to.meta.requireAuth && !token) {
    next('/login')
  } else if (to.meta.roles && !checkRole(to.meta.roles as Role[])) {
    ElMessage.error('您没有权限访问该页面')
  } else {
    next()
  }
  console.log(from)

  // if (to.path === '/login' || to.path === '/' || to.path === '/register') {
  //   next()
  // } else {
  //   if (token) {
  //     next()
  //   } else {
  //     next('/login')
  //   }
  // }
})

//根据角色检测权限
const checkRole = (roles: Role[]) => {
  const userStore = useUserStore()
  const role = userStore.userInfo.role as Role
  return roles.includes(role)
}

//后置路由守卫
router.afterEach((to) => {
  document.title = to.meta.title as string
})

export default router
